local MultiPlatform = appdf.req(appdf.EXTERNAL_SRC .. "MultiPlatform")
local AgentsLayer = class("AgentsLayer", function(scene)
	local newLayer = display.newLayer(cc.c4b(0, 0, 0, 180))
	return newLayer
end)
local utils = appdf.req(appdf.EXTERNAL_SRC .. "Utils")
local ExternalFun = appdf.req(appdf.EXTERNAL_SRC .. 'ExternalFun')
local AlipayLayer = appdf.req(appdf.CLIENT_SRC .. 'plaza.views.layer.plaza.BindAlipayLayer')
local BindBankLayer = appdf.req(appdf.CLIENT_SRC .. 'plaza.views.layer.plaza.BindBankLayer')
local LEFT_GOLD = 10000  --至少留10
local Utils = appdf.req(appdf.EXTERNAL_SRC .. "Utils")
local SUCCESS_CODE = 10000
local tbwechatpos = {{cc.p(679,415)},
					 {cc.p(679,475),cc.p(679,365)},
					{cc.p(679,525),cc.p(679,415),cc.p(679,306)}

}
function AgentsLayer:ctor(_scene)
    self._scene = _scene
	self.is_qmagent = _scene.is_qmagent
	ExternalFun.registerNodeEvent(self)
    self.currentPage = 1
    self.exchangeRecords = {}
	self.records = {}
	self:loadCSB()
    -- self:initUI()
	
	--	utils.openWebViewURL("http://45.119.97.72:800",self,cc.size(display.width,display.height-100),_pos)
end
function AgentsLayer:getserverConfig()
	return self._scene:getApp()._serverConfig
end
function AgentsLayer:loadCSB()
	local root,rootnode = ExternalFun.loadCSB("agentLayer/AgentLayer.csb", self)
	self.csbNode = root
	self.img_Bg = root:getChildByName("img_exchangebg")
	ExternalFun.FixTopUI(root)
    self.csbNode:setPositionY((display.height-750)/2)

    local btncallback = function(ref,type)
        if type == ccui.TouchEventType.ended then
			ref:setScale(1)
			ExternalFun.playClickEffect()
            self:onButtonClicked(ref:getTag(),ref)
		elseif type == ccui.TouchEventType.began then
			ref:setScale(yl.btscale)
			return true
		elseif type == ccui.TouchEventType.canceled then  
			ref:setScale(1)
        end
    end
    
    self.btn_close = self.img_Bg:getChildByName("btn_close")
    self.btn_close:addTouchEventListener(btncallback)

    self.btn_listview = self.img_Bg:getChildByName("btn_listview")
	self.yuerubtn = self.btn_listview:getChildByName("yuerubtn")
	self.mytuig = self.btn_listview:getChildByName("mytuig")
    self.btn_guize = self.btn_listview:getChildByName("btn_guize") 

    self.yuerubtn:setTag(1)
    self.mytuig:setTag(2)
    self.btn_guize:setTag(3)
    
    self.yuerubtn:addTouchEventListener(btncallback)
    self.mytuig:addTouchEventListener(btncallback)
    self.btn_guize:addTouchEventListener(btncallback)

	self.layer_record = self.img_Bg:getChildByName("layer_record")
	self.myzhishu = self.layer_record:getChildByName("myzhishu")
	self.mylevel = self.layer_record:getChildByName("mylevel")
	self.myxiaji = self.layer_record:getChildByName("myxiaji")
	self.ly_recordDemo = root:getChildByName("ly_recordItem")
	
    self.layer_yueru = self.img_Bg:getChildByName("layer_yueru")
	self.layer_yueru:setVisible(false)
    self.yuerubtn:setEnabled(false)
    
    self.layer_tuig = self.img_Bg:getChildByName("layer_tuig")
	self.layer_tuig:setVisible(false)
    self.mytuig:setEnabled(false)
    
    self.layer_guize = self.img_Bg:getChildByName("layer_guize")
	self.layer_guize:setVisible(false)
    self.btn_guize:setEnabled(false)
    self.bindbtn = self.layer_yueru:getChildByName("bindbtn")
	self.input_bg = self.layer_yueru:getChildByName("input_bg")
	
	self.introduction = self.img_Bg:getChildByName("introductionLayer")
	self.introduction:setVisible(false)
	self.introductionClose = self.introduction:getChildByName("closebtn")
	self.introductionClose:addTouchEventListener(btncallback)
	self.introductionbtn = self.layer_yueru:getChildByName("introductionbtn")
	self.introductionbtn:addTouchEventListener(btncallback)


	local accountinfo = GlobalUserItem.getAccountInfo()
	self.myid = self.layer_yueru:getChildByName("myid")
	self.myid:setString(GlobalUserItem.dwUserID)

	self.link_text  = self.layer_yueru:getChildByName("link_text")
	self.extension_url = "http://www.tgoyh.cn?id=" .. GlobalUserItem.dwUserID
	self.link_text:setString(self.extension_url)

	self.ercodenode = self.layer_yueru:getChildByName("ercodenode")
	self.qr = QrNode:createQrNode(self.extension_url, 216, 5, 2)
    self.ercodenode:addChild(self.qr)
	-- qr:setPosition(self.cb_music:getPosition())
	-- local vcallback = function(save_path)
	-- 	dump(save_path)
	-- end

	-- qr:saveQrToFile("qrrr.png",vcallback)


    self.qqbtn = self.layer_yueru:getChildByName("qqbtn")
    self.wxbtn = self.layer_yueru:getChildByName("wxbtn")

    self.saveercodebtn = self.layer_yueru:getChildByName("saveercodebtn")
    
    self.copyhttpbtn = self.layer_yueru:getChildByName("copyhttpbtn")
	self.text_tuijian = self.layer_yueru:getChildByName("text_tuijian")
	self.copybtn = self.layer_yueru:getChildByName("copybtn")

    local btncallback = function(ref,type)
        if type == ccui.TouchEventType.ended then
			ExternalFun.playClickEffect()
            self:onButtonClicked(ref:getTag(),ref)
        end
    end
    self.qqbtn:addTouchEventListener(btncallback)
    self.wxbtn:addTouchEventListener(btncallback)
    self.bindbtn:addTouchEventListener(btncallback)
    self.saveercodebtn:addTouchEventListener(btncallback)
    self.copyhttpbtn:addTouchEventListener(btncallback)
	self.link_text:addTouchEventListener(btncallback)
	self.copybtn:addTouchEventListener(btncallback)

	if not self.tf_tuijian then
		self.tf_tuijian = ccui.EditBox:create(cc.size(300,40),ccui.Scale9Sprite:create(""))
			:setAnchorPoint(cc.p(0,0))
			:setPosition(cc.p(10,20))
			:setFontSize(28)
			:setInputMode(cc.EDITBOX_INPUT_MODE_NUMERIC)
			:setMaxLength(15)
			:setPlaceHolder("请输入推荐人ID:")
	end
	self.input_bg:addChild(self.tf_tuijian)
    self.tf_tuijian:registerScriptEditBoxHandler(function(event,editbox)
        if event == "return" or event == "changed" then
            self.tuijianrenID = editbox:getText()
        end
    end)

	self:showLayer(1)

	ExternalFun.FixScaleUI(self.layer_yueru)
	ExternalFun.FixScaleUI(self.layer_tuig)
	ExternalFun.FixScaleUI(self.layer_guize)
	ExternalFun.FixScaleUI(self.layer_record)
	local ChannelType = self._scene:getChannelType()
	self:setbindVisible(ChannelType == 3)
	
end

function AgentsLayer:onButtonClicked(tag,ref)
    if ref == self.btn_close then
        self._scene:onKeyBack()
    elseif ref == self.yuerubtn then --月入百万
        self:showLayer(1)
    elseif ref == self.mytuig then -- 我的推广
        self:showLayer(2)
    elseif ref == self.btn_guize then --收益规则
		self:showLayer(3)
	elseif ref == self.saveercodebtn then
		local vcallback = function(save_path)
			local ret = MultiPlatform:saveImgToSystemGallery(save_path, "tgqrcode.png")
			if ret then
				showToast(self,"保存二维码到相册成功",1)
			end
		end
		self.qr:saveQrToFile("tgqrcode.png",vcallback)
	elseif ref == self.copybtn then
		self:copyInfo(self.myid:getString())
    elseif ref == self.qqbtn then    
        utils.checkAPPInstalled("qqpay","QQ未安装，请安装后重试")
		cc.Application:getInstance():openURL("mqq://im/chat?chat_type=wpa")
		self:copyInfo(self.extension_url)
    elseif ref == self.wxbtn then    
        utils.checkAPPInstalled("wxpay","微信未安装，请安装后重试")
		cc.Application:getInstance():openURL("weixin://")
		self:copyInfo(self.extension_url)
    elseif ref == self.copyhttpbtn then  
		self:copyInfo(self.extension_url)
	elseif ref == self.btnclose_deltail then
		self.layer_record:setVisible(false)
		self.layer_tuig:setVisible(true)
		-- local templayer = self.layer_record:getChildByName(self.viewname)
		-- if templayer then
		-- 	templayer:setVisible(false)
		-- end
	elseif ref == self.bindbtn then 
		if not  self.tuijianrenID or trim(self.tuijianrenID) == "" then 
			showToast(self,"推荐人id不能为空",1)
			return
		end
		local function cb( data )
			if self.text_tuijian  then
				if data.code == SUCCESS_CODE then
					self.text_tuijian:setString("您已经绑定了推荐人玩家ID:"..self.tuijianrenID)	
					self.text_tuijian:setVisible(true)
					self.input_bg:setVisible(false)
					self.bindbtn:setVisible(false)
				else
					self.text_tuijian:setString("")
				end
			end
			showToast(self,data.msg or "绑定成功",1)
		end
        utils.bindTuiJiaRen( {invitecode=self.tuijianrenID},cb )
    elseif ref == self.link_text then 

	elseif ref == self.xiajibtn then 
		self.viewname = "myxiaji"
		-- local templayer = self.layer_record:getChildByName(self.viewname )
		-- templayer:setVisible(true)
		self.layer_record:setVisible(true)
		self.myzhishu:setVisible(false)
		self.myxiaji:setVisible(true)
		self.mylevel:setVisible(false)

		self.layer_tuig:setVisible(false)
		if not self[self.viewname.."cur_page"]  then
			utils.getMyProfitXiaji( {type=2,page=1},handler(self,self.getMyXiajiProfit) )
		end

		
	elseif ref == self.zhishubtn then 
		self.viewname = "myzhishu"
		-- local templayer = self.layer_record:getChildByName(self.viewname )
		-- templayer:setVisible(true)

		self.layer_record:setVisible(true)
		self.myzhishu:setVisible(true)
		self.myxiaji:setVisible(false)
		self.mylevel:setVisible(false)
		

		self.layer_tuig:setVisible(false)
		if not self[self.viewname.."cur_page"]  then
			utils.getMyProfitZhishu( {type=1,page=1},handler(self,self.getMyZhiShuProfit) )
			self[self.viewname.."inloading"] =  true
		end
	elseif ref == self.myzhishubtn then 
		self.viewname = "mylevel"
		self.myzhishu:setVisible(false)
		self.myxiaji:setVisible(false)
		self.mylevel:setVisible(true)
	
		self.layer_record:setVisible(true)
		self.layer_tuig:setVisible(false)
		-- self[self.viewname.."cur_page"] = self[self.viewname.."cur_page"] or 1
		if not self[self.viewname.."cur_page"]  then
			utils.getMyLevel( {page=1},handler(self,self.getMyLevel) )
			self[self.viewname.."inloading"] =  true
		end
	elseif ref == self.getyongjinbtn then 
		local function cb( data )
			if self.use_peofit  then
				if data.code == SUCCESS_CODE then
				self:getTuiguangDetail()
			--	total_profit:setString(data.total_profit)
			print("showArrivalLayerupdateInfomation")
					self._scene:updateInfomation()
					 --由于领取后会触发充值到帐协议 所以用这个字段过滤掉充值到帐
					self._scene.isgetYongjin = true
					
					utils.showArrivalLayer(ExternalFun.ChangeScore(tonumber(data.score),2,",") ,nil,self)
				else
					self.text_tuijian:setString("")
				end
			end
			
			showToast(self,data.msg or "获取成功",1)
		end
	--	utils.showArrivalLayer(1,nil,self)
		utils.toGetPeofit( {},cb )
	elseif ref == self.introductionClose then
		
		self.introduction:setVisible(false)
	elseif ref == self.introductionbtn then
		-- self:initIntroductionLayer()

		-- by djy 修改获取全民代理中的客服qq和微信
		local params = "123"
		--local sign = MD5Json(params)
		local sign = md5(params)
		local params = "js="..params.."&sign="..sign
		local http_api = self:getserverConfig().http_api.."allagent/connectmethod?"
		appdf.onHttpJsionTable(http_api..os.time(),"POST",params,
		function(jsondata,response)
			local weixintb  = jsondata.connectWC
			local QQtb  = jsondata.connectQQ
			QQtb = QQtb or {}
			self.introduction:setVisible(true)
			local itemwechat = self.introduction:getChildByName("wechatdemo")
			weixintb = weixintb or {}
			local partitionNum = #weixintb
			for k,v in pairs(QQtb) do  
				weixintb[#weixintb + k] = v
			end
			if #weixintb <= 0 then
				itemwechat:setVisible(false)
				return
			else
				itemwechat:setVisible(true)
			end
			for i=1,#weixintb do
				if i >3 then
					return
				end
				local tablelen = #weixintb > 3 and 3 or #weixintb
				local item 
				if i > 1 then
					if self.introduction:getChildByTag(i) then
						item = self.introduction:getChildByTag(i)
					else
					item = itemwechat:clone()
					item:setTag(i)
					self.introduction:addChild(item)
					end
				else
					item = itemwechat
					
				end
				item:setPosition(tbwechatpos[tablelen][i])
				local wechat_txt = item:getChildByName("wechat_txt")
				wechat_txt:setString(weixintb[i] or "获取微信号失败")
				
				local copyWX_btn = item:getChildByName("copywx_btn")
				copyWX_btn:addTouchEventListener(function (ref, type)
				if type == ccui.TouchEventType.ended then
					ExternalFun.playClickEffect( )
					local weixin = weixintb[i]
		
					local ret, msg = MultiPlatform:copyToClipboard(weixin)
					if ret == true then
						showToast(self, "复制成功!", 1)
					else
						showToast(self, msg or "复制失败", 1, cc.c3b(250, 0, 0))
					end
					if i > partitionNum then
						Utils.checkAPPInstalled("qqpay")
						cc.Application:getInstance():openURL("mqq://im/chat?chat_type=wpa")
					else
					Utils.checkAPPInstalled("wxpay")
					cc.Application:getInstance():openURL("weixin://")
					end
					ref:setScale(1)
				elseif type == ccui.TouchEventType.began then
					ref:setScale(yl.btscale)
					return true
				elseif type == ccui.TouchEventType.canceled then  
					ref:setScale(1)
				end
			end)
				if i > partitionNum then
					local img = item:getChildByName("Image_1")
					img:ignoreContentAdaptWithSize(true)
					img:loadTexture("Shop/qqdl.png")
					copyWX_btn:loadTextures("Shop/openqq.png","Shop/openqq.png")
				end
			end
		end)
    end
end
function AgentsLayer:initIntroductionLayer()
--tbwechatpos
	local weixintb  = clone(self:getserverConfig().connectWC) 
	local QQtb  = clone(self:getserverConfig().connectQQ) 
	QQtb = QQtb or {}
	self.introduction:setVisible(true)
	local itemwechat = self.introduction:getChildByName("wechatdemo")
	weixintb = weixintb or {}
	local partitionNum = #weixintb
	for k,v in pairs(QQtb) do  
		weixintb[#weixintb + k] = v
	end
	if #weixintb <= 0 then
		itemwechat:setVisible(false)
		return
	else
		itemwechat:setVisible(true)
	end
	for i=1,#weixintb do
		if i >3 then
			return
		end
		local tablelen = #weixintb > 3 and 3 or #weixintb
		local item 
		if i > 1 then
			if self.introduction:getChildByTag(i) then
				item = self.introduction:getChildByTag(i)
			else
			item = itemwechat:clone()
			item:setTag(i)
			self.introduction:addChild(item)
			end
		else
			item = itemwechat
			
		end
		item:setPosition(tbwechatpos[tablelen][i])
		local wechat_txt = item:getChildByName("wechat_txt")
		wechat_txt:setString(weixintb[i] or "获取微信号失败")
		
		local copyWX_btn = item:getChildByName("copywx_btn")
		copyWX_btn:addTouchEventListener(function (ref, type)
		if type == ccui.TouchEventType.ended then
			ExternalFun.playClickEffect( )
			local weixin = weixintb[i]

			local ret, msg = MultiPlatform:copyToClipboard(weixin)
			if ret == true then
				showToast(self, "复制成功!", 1)
			else
				showToast(self, msg or "复制失败", 1, cc.c3b(250, 0, 0))
			end
			if i > partitionNum then
				Utils.checkAPPInstalled("qqpay")
				cc.Application:getInstance():openURL("mqq://im/chat?chat_type=wpa")
			else
			Utils.checkAPPInstalled("wxpay")
			cc.Application:getInstance():openURL("weixin://")
			end
			ref:setScale(1)
		elseif type == ccui.TouchEventType.began then
			ref:setScale(yl.btscale)
			return true
		elseif type == ccui.TouchEventType.canceled then  
			ref:setScale(1)
		end
	end)
		if i > partitionNum then
			local img = item:getChildByName("Image_1")
			img:ignoreContentAdaptWithSize(true)
			img:loadTexture("Shop/qqdl.png")
			copyWX_btn:loadTextures("Shop/openqq.png","Shop/openqq.png")
		end
	end

end
function AgentsLayer:getMyLevel( data )
	
	local cur_page = self[self.viewname.."cur_page"]
	cur_page = cur_page or 1
	if data.code ~= SUCCESS_CODE then
		if cur_page == 1 then
			showToast(self,"您还未推广玩家，赶快推广一起来赚钱！",1)
		else
			showToast(self,data.msg or "数据获取失败",1)
		end
		
		return
	end
	-- local templayer = self.layer_record:getChildByName("mylevel")
	-- if not templayer:isVisible() then
	-- 	return
	-- end
	if not self["mylevelrecords"]   then
		self["mylevelrecords"]  = {}
	end
	for i,v in pairs(data.list) do
		table.insert( self["mylevelrecords"] , v )
	end
	self["mylevelcur_page"]  = self["mylevelcur_page"]  or 1
	self["mylevelinloading"] = false
	self["mylevelcount_page"] = data.count_page 

	self:handleRecords(self["mylevelrecords"] or {},"mylevel",#data.list)
	
end

function AgentsLayer:getMyZhiShuProfit( data )
	
	local cur_page = self[self.viewname.."cur_page"]
	cur_page = cur_page or 1
	if data.code ~= SUCCESS_CODE then
		if cur_page == 1 then
			showToast(self,"您还未推广玩家，赶快推广一起来赚钱！",1)
		else
			showToast(self,data.msg or "数据获取失败",1)
		end
		
		return
	end
	-- local templayer = self.layer_record:getChildByName("myzhishu")
	-- if not templayer:isVisible() then
	-- 	return
	-- end
	
	if not self["myzhishurecords"]   then
		self["myzhishurecords"]  = {}
	end
	for i,v in pairs(data.list) do
		table.insert( self["myzhishurecords"] , v )
	end
	self["myzhishucur_page"]  = self["myzhishucur_page"]  or 1
	self["myzhishuinloading"] = false
	self["myzhishucount_page"] = data.count_page 


	self:handleRecords(self["myzhishurecords"],"myzhishu",#data.list)
	
end

function AgentsLayer:getMyXiajiProfit( data )
	local cur_page = self[self.viewname.."cur_page"]
	cur_page = cur_page or 1
	if data.code ~= SUCCESS_CODE then
		if cur_page == 1 then
			showToast(self,"您还未推广玩家，赶快推广一起来赚钱！",1)
		else
			showToast(self,data.msg or "数据获取失败",1)
		end
		
		return
	end

	-- local templayer = self.layer_record:getChildByName("myxiaji")
	-- if not templayer:isVisible() then
	-- 	return
	-- end

	if not self["myxiajirecords"]   then
		self["myxiajirecords"]  = {}
	end
	for i,v in pairs(data.list) do
		table.insert( self["myxiajirecords"] , v )
	end
	self["myxiajicur_page"]  = self["myxiajicur_page"]  or 1
	self["myxiajiinloading"] = false
	self["myxiajicount_page"] = data.count_page 
	self:handleRecords(self["myxiajirecords"],"myxiaji",#data.list)

end

function AgentsLayer:onExit()
	-- appdf.removeListener(self.tb_listen)
end


	
function AgentsLayer:cellSizeForTable( view, idx)
	return 997,53
end

function AgentsLayer:tableCellAtIndex( view, idx)
	
	local cell = view:dequeueCell()
	local item = nil
	local itemdate = self[self.viewname.."records"][idx+1] --self.records[idx+1]
	if nil == cell then
		cell = cc.TableViewCell:new()
		item = self.ly_recordDemo:clone()
		item:setName("recorditem")
		item:setVisible(true)
		item:setPosition(0,0)
		cell:addChild(item)
		
	else
		item = cell:getChildByName("recorditem")	
	end
	local dataname = {
		mylevel = {"date","uid","level_num","profit"},
		myxiaji = {"date","tax","rate","profit"},
		myzhishu = {"date","tax","rate","profit"},
	}
	 

	local txt_1 =  item:getChildByName("txt_1")
	local txt_2 =  item:getChildByName("txt_2")
	local txt_3 =  item:getChildByName("txt_3")
	local txt_4 =  item:getChildByName("txt_4")
	txt_1:setString(itemdate[dataname[self.viewname][1]])
	txt_2:setString(itemdate[dataname[self.viewname][2]])
	txt_3:setString(itemdate[dataname[self.viewname][3]])
	txt_4:setString(itemdate[dataname[self.viewname][4]])
	self.lastTableViewIdx =idx 
	return cell
end


function AgentsLayer:numberOfCellsInTableView(view)
	-- showToast(self,"numberOfCellsInTableView>>"..#self[self.viewname.."records"],1)
	return self[self.viewname.."records"] and #self[self.viewname.."records"] or 0
end

function AgentsLayer:showLayer(idx)
    if idx > 3 or idx < 1 then
        self:showLayer(1)
        return
    end

    if idx == 1 then
        self.layer_yueru:setVisible(true)
        self.layer_tuig:setVisible(false)
        self.layer_record:setVisible(false)
        self.layer_guize:setVisible(false)
		if self.yuerubtn then
			self.yuerubtn:setEnabled(false)
		end
		
		if self.mytuig then
			self.mytuig:setEnabled(true) 
		end
		self.btn_guize:setEnabled(true)
		
		self.currentPage = 1
		
		self:getAgentInfo()
    elseif idx == 2 then
        self.layer_yueru:setVisible(false)
        self.layer_tuig:setVisible(true)
        self.layer_record:setVisible(false)
		self.layer_guize:setVisible(false)
		self.layer_record:getChildByName("myzhishu"):setVisible(false)
		self.layer_record:getChildByName("mylevel"):setVisible(false)
		self.layer_record:getChildByName("myxiaji"):setVisible(false)
		if self.yuerubtn then
			self.yuerubtn:setEnabled(true)
		end
		
		if self.mytuig then
			self.mytuig:setEnabled(false) 
		end
		self.btn_guize:setEnabled(true)
		self.currentPage = 2
		self:getTuiguangDetail()
    elseif idx == 3 then
        if self.currentPage == 3 then
            return
        end
        self.currentPage = 3
        self.layer_yueru:setVisible(false)
        self.layer_tuig:setVisible(false)
        self.layer_record:setVisible(false)
        self.layer_guize:setVisible(true)
		if self.yuerubtn then
			self.yuerubtn:setEnabled(true)
		end
		
		if self.mytuig then
			self.mytuig:setEnabled(true) 
		end
        self.btn_guize:setEnabled(false)
        
		-- self.layer_record:setEnabled(false)
		-- local intervalTime = os.time() - (GlobalUserItem.FreshExcahngeRecordsTime or 0)
		-- if GlobalUserItem.myAgentRecords == nil or intervalTime > 30 then
		-- 	self:getAgentRecords()
		-- 	self:showPopWait()
		-- else
		-- 	self:handleRecords(GlobalUserItem.myAgentRecords)
		-- end
        
    end
end

function AgentsLayer:getAgentInfo()
    if self.agentInfo then
		return
	end
    utils.getAgentsInfo( jsontab,handler(self,self.handleAgentInfo) )
end

function AgentsLayer:getTuiguangDetail()
    utils.getTuiguangDetail( jsontab,handler(self,self.handleTuiGuangDetail) )
end
--设置是否可以绑定
function AgentsLayer:setbindVisible(bvisi)
    self.input_bg:setVisible(bvisi)
	self.bindbtn:setVisible(bvisi)
end


function AgentsLayer:handleAgentInfo(data)
	if data.code ~= SUCCESS_CODE then
		showToast(self,data.msg or "数据获取失败",1)
		return
	end
	
	self.agentInfo = data or {}
	if tolua.isnull(self.layer_yueru) then
		return
	end
	self.myid = self.layer_yueru:getChildByName("myid")

    self.qqbtn = self.layer_yueru:getChildByName("qqbtn")
    self.wxbtn = self.layer_yueru:getChildByName("wxbtn")

    self.saveercodebtn = self.layer_yueru:getChildByName("saveercodebtn")
    self.ercodenode = self.layer_yueru:getChildByName("ercodenode")
    
    self.copyhttpbtn = self.layer_yueru:getChildByName("copyhttpbtn")
	self.link_text  = self.layer_yueru:getChildByName("link_text")
	self.text_tuijian = self.layer_yueru:getChildByName("text_tuijian")
	self.copybtn = self.layer_yueru:getChildByName("copybtn")
	
	self.myid:setString(data.myID)
	self.qcode_url = data.qcode_url
	self.extension_url = data.extension_url

	local str = appdf.stringByEllipsis(data.extension_url, 10,20,350,"\n")
	self.link_text:setString(str)
	self:loadqcode(self.qcode_url,self.ercodenode)
	

    local btncallback = function(ref,type)
        if type == ccui.TouchEventType.ended then
			ExternalFun.playClickEffect()
            self:onButtonClicked(ref:getTag(),ref)
        end
    end
    self.qqbtn:addTouchEventListener(btncallback)
    self.wxbtn:addTouchEventListener(btncallback)
    self.bindbtn:addTouchEventListener(btncallback)
    self.saveercodebtn:addTouchEventListener(btncallback)
    self.copyhttpbtn:addTouchEventListener(btncallback)
	self.link_text:addTouchEventListener(btncallback)
	self.copybtn:addTouchEventListener(btncallback)

	local is_extension = data.is_extension
	self.text_tuijian:setVisible(is_extension == 1)
	if is_extension == 1 then
		self.text_tuijian:setString("您已绑定了推荐码，推荐人ID:"..data.extension_id)	
		self.text_tuijian:setVisible(true)
		self.input_bg:setVisible(false)
		self.bindbtn:setVisible(false)
		return 
	end
	if not self.tf_tuijian then
		self.tf_tuijian = ccui.EditBox:create(cc.size(300,40),ccui.Scale9Sprite:create(""))
			:setAnchorPoint(cc.p(0,0))
			:setPosition(cc.p(10,20))
			:setFontSize(28)
			:setInputMode(cc.EDITBOX_INPUT_MODE_NUMERIC)
			:setMaxLength(15)
			:setPlaceHolder("请输入推荐人ID:")
		self.input_bg:addChild(self.tf_tuijian)   -- by djy 第二次添加到父节点，移动了位置
	end
	self.tuijianrenID = nil
    self.tf_tuijian:registerScriptEditBoxHandler(function(event,editbox)
        if event == "return" or event == "changed" then
            self.tuijianrenID = editbox:getText()
        end
    end)
	local AngetType = self._scene:getAngetType()
	if self.is_qmagent ~= 1 and AngetType == 3 then
		MultiPlatform:getInstance():getClipboardData(function (data)
		local pstart,pend = string.find(data,"weitjqm%-")
		local myidStr =  self.myid:getString()
		local getBindQMByIp = cc.UserDefault:getInstance():getBoolForKey("getBindQMByIp",false)
		if self.tf_tuijian and myidStr ~= str and  pend then
		local str = string.sub(data,pend+1,string.len(data))
			if not appdf.isNullString( str )  then
		pstart,pend = string.find(str,"%.")
		if pend then
			str = string.sub(str,1,pend-1)
		end
			self.tf_tuijian:setText(str)
			self.tuijianrenID = str
			self:onButtonClicked(self.bindbtn:getTag(),self.bindbtn)
			elseif not getBindQMByIp then	
			--	utils.getBindMoreByIp( {bindtype = 1} )
			--	cc.UserDefault:getInstance():setBoolForKey("getBindQMByIp",true)
			end
		elseif not getBindQMByIp then	
		--	utils.getBindMoreByIp( {bindtype = 1} )
		--	cc.UserDefault:getInstance():setBoolForKey("getBindQMByIp",true)
		end
		end)
	elseif self.is_qmagent == 1 and is_extension == 0 then
		self.text_tuijian:setVisible(false)
		self.input_bg:setVisible(false)
		self.bindbtn:setVisible(false)
	end
	
end	

function AgentsLayer:loadqcode(qrcodeurl,ercodenode,bshowTip)

	local localqrurl = cc.UserDefault:getInstance():getStringForKey("tgqrcode", "")
	local savePath = cc.FileUtils:getInstance():getWritablePath() .. "download/"

	print("loadqcode>>>>",qrcodeurl,savePath)
	local callback = function( ret )
		if ret == appdf.DOWN_COMPELETED then
			if  ercodenode  then
				local sp = ccui.Button:create(savePath.."tgqrcode.jpg")--display.newSprite(savePath.."tgqrcode.png")
				local size = sp:getContentSize()
				sp:setScale(216/size.width)
				ercodenode:addChild(sp)
				sp:addTouchEventListener(function(sender, eventType)
					if eventType == ccui.TouchEventType.ended then
						ExternalFun.playClickEffect()
						local ret = MultiPlatform:saveImgToSystemGallery(savePath.."tgqrcode.jpg", "tgqrcode.jpg")
						if ret then
							showToast(self,"保存二维码到相册成功",1)
						end
					end
				
				end)
				cc.UserDefault:getInstance():setStringForKey("tgqrcode",qrcodeurl)
			end
			
		end
	end
	
	if localqrurl == qrcodeurl and cc.FileUtils:getInstance():isFileExist(savePath.."tgqrcode.jpg")  then
		callback(appdf.DOWN_COMPELETED)
		return
	end

	appdf.onHttpDownUrl(qrcodeurl.."?"..os.time(),"tgqrcode.jpg",savePath,callback )
end

function AgentsLayer:handleTuiGuangDetail(data)
	if data.code ~= SUCCESS_CODE then
		showToast(self,data.msg or "数据获取失败",1)
		return
	end
	if tolua.isnull(self.layer_tuig) then
		return
	end
	self.records = recordsData or {}
    self.xiajibtn = self.layer_tuig:getChildByName("xiajibtn")
    self.zhishubtn = self.layer_tuig:getChildByName("zhishubtn")
    self.myzhishubtn = self.layer_tuig:getChildByName("myzhishubtn")

	local  zhishuMoney = self.layer_tuig:getChildByName("zhishuMoney")
	local  zhishuinfo = self.layer_tuig:getChildByName("zhishuinfo")

	local xiajiMoney = self.layer_tuig:getChildByName("xiajiMoney")
	local xiajiinfo = self.layer_tuig:getChildByName("xiajiinfo")

    local  peopleAltas = self.layer_tuig:getChildByName("peopleAltas")
    local  total_profit = self.layer_tuig:getChildByName("total_profit")
	self.use_peofit = self.layer_tuig:getChildByName("use_peofit")
	self.getyongjinbtn = self.layer_tuig:getChildByName("getyongjinbtn")

	self.btnclose_deltail = self.layer_record:getChildByName("btnclose_deltail")
	
	-- by djy  修改字段与现有web返回值一致  lower_profit llower_profit
	zhishuMoney:setString(data.yesday_lprofit)
	xiajiMoney:setString(data.yesday_llprofit)

	peopleAltas:setString(data.level_num)

	total_profit:setString(data.total_profit)
	self.can_use_peofit = data.use_peofit
	self.use_peofit:setString("佣金次日01:30后可以领取")--string.format(,data.total_profit,data.use_peofit)

	--[[zhishuinfo:setString(string.format("昨日直属下级税收%d金币佣金比例%s",data.yesday_lprofit,data.yesday_lrate))
	xiajiinfo:setString(string.format("昨日次级下级税收%d金币佣金比例%s",data.yesday_llprofit,data.yesday_llrate))--]]
	
	zhishuinfo:setString(string.format("直属下级佣金比例%s",data.yesday_lrate))
	xiajiinfo:setString(string.format("次级下级佣金比例%s",data.yesday_llrate))

    local btncallback = function(ref,type)
        if type == ccui.TouchEventType.ended then
			ExternalFun.playClickEffect()
            self:onButtonClicked(ref:getTag(),ref)
			ref:setScale(1)
		elseif type == ccui.TouchEventType.began then
			ref:setScale(yl.btscale)
			return true
		elseif type == ccui.TouchEventType.canceled then
			ref:setScale(1)
        end
    end
	self.btnclose_deltail:addTouchEventListener(btncallback)
    self.xiajibtn:addTouchEventListener(btncallback)
    self.zhishubtn:addTouchEventListener(btncallback)
    self.myzhishubtn:addTouchEventListener(btncallback)
	self.getyongjinbtn:addTouchEventListener(btncallback)
end	

function AgentsLayer:copyInfo(info)
	local ret, msg = MultiPlatform:copyToClipboard(info)
	if ret == true then
		showToast(self, "复制成功!", 1)
	else
		if type(msg) == "string" then
			showToast(self, msg, 1, cc.c3b(250, 0, 0))
		end
	end
end

function AgentsLayer:handleRecords(recordsData,viewname,addcount)
	-- self.viewname = viewname
	local templayer = self.layer_record:getChildByName(viewname)
	-- templayer:setVisible(true)
	if not self[viewname.."recordTabView"] then
		local size = templayer:getContentSize()
		size.height = size.height - 113
		local recordTabView = cc.TableView:create(size)-- cc.size(993,518)
		self[viewname.."recordTabView"] = recordTabView
		recordTabView:setDirection(cc.SCROLLVIEW_DIRECTION_VERTICAL)
		local px,py = templayer:getPosition()
		-- recordTabView:setPosition(cc.p(px+10,py-50))--cc.p(18,50)  templayer:getPosition()
		recordTabView:setDelegate()
		recordTabView:setVerticalFillOrder(cc.TABLEVIEW_FILL_TOPDOWN)
		recordTabView:registerScriptHandler(handler(self, self.cellSizeForTable), cc.TABLECELL_SIZE_FOR_INDEX)
		recordTabView:registerScriptHandler(handler(self, self.tableCellAtIndex), cc.TABLECELL_SIZE_AT_INDEX)
		recordTabView:registerScriptHandler(handler(self, self.numberOfCellsInTableView), cc.NUMBER_OF_CELLS_IN_TABLEVIEW)
		recordTabView:registerScriptHandler(handler(self, self.tableCellRecyle), cc.TABLECELL_WILL_RECYCLE)
		recordTabView:registerScriptHandler(handler(self, self.tableCellTouched), cc.TABLECELL_TOUCHED)
		templayer:addChild(recordTabView)
		recordTabView:reloadData()
	else
		addcount = addcount or 0
		self[viewname.."recordTabView"]:reloadData()
		local offset = self[viewname.."recordTabView"]:maxContainerOffset()
		self[viewname.."recordTabView"]:setContentOffset(cc.p(offset.x,offset.y-addcount*51),false)
		
		-- local targetidx = self.curCellIndex or #recordsData-5
		-- showToast(self,"updateCellAtIndex "..targetidx,1)
	-- 	performWithDelay(self,function( ... )
	-- 		-- body
	-- 		self[viewname.."recordTabView"]:updateCellAtIndex(targetidx)
	-- 	end,1)
	end
	

end	

function AgentsLayer:tableCellTouched(view, cell)
	-- ExternalFun.playClickEffect( )
	-- self.curCellIndex = cell:getIdx()+1

end


function AgentsLayer:tableCellRecyle(view, cell)
	local delta = #self[self.viewname.."records"] -cell:getIdx()
	local tempnum = self.lastTableViewIdx - cell:getIdx()
	--print("tableCellRecyletableCellRecyle",tempnum)
	if delta == 10 and not self[self.viewname.."inloading"] and tempnum > 0 then
		if self.viewname == "mylevel" then
			local cur_page = self[self.viewname.."cur_page"]
			local count_page = self[self.viewname.."count_page"]
			if cur_page < count_page then
				cur_page = cur_page + 1
			--	showToast(self,"load page "..cur_page,1)
				utils.getMyLevel( {page=cur_page},handler(self,self.getMyLevel) )
				self[self.viewname.."inloading"] =  true
				self[self.viewname.."cur_page"] = cur_page
			end
		elseif self.viewname == "myxiaji" then
			local cur_page = self[self.viewname.."cur_page"]
			local count_page = self[self.viewname.."count_page"]
			if cur_page < count_page then
				cur_page = cur_page + 1
			--	showToast(self,"load page "..cur_page,1)
				utils.getMyProfitXiaji( {type=2,page=cur_page},handler(self,self.getMyXiajiProfit) )
				self[self.viewname.."inloading"] =  true
				self[self.viewname.."cur_page"] = cur_page
			end
		elseif self.viewname == "myzhishu" then
		
			local cur_page = self[self.viewname.."cur_page"]
			local count_page = self[self.viewname.."count_page"]
			if cur_page < count_page then
				cur_page = cur_page + 1
			--	showToast(self,"load page "..cur_page,1)
				utils.getMyProfitZhishu( {type=1,page=cur_page},handler(self,self.getMyZhiShuProfit) )
				self[self.viewname.."inloading"] =  true
				self[self.viewname.."cur_page"] = cur_page
			end
		end
	end
	ExternalFun.playClickEffect( )
	-- self:ClickMailCell(cell:getIdx()+1,cell)
end





--显示等待
function AgentsLayer:showPopWait()
	self._scene:showPopWait()
end

--关闭等待
function AgentsLayer:dismissPopWait()
	self._scene:dismissPopWait()
end
return AgentsLayer 